#include "testnet.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>

TestNet::TestNet(QObject *parent) : QObject(parent)
{

}

void TestNet::test()
{
    m_manager = new QNetworkAccessManager();
    m_request = new QNetworkRequest(QUrl("https://172.21.2.46/login"));

    QSslConfiguration conf = m_request->sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyPeer);
    conf.setProtocol(QSsl::TlsV1SslV3);

    QFile crt("F:\\SWPCCamFWUpdatePlatformRepository\\trunk\\MyWorks\\FUManager\\Debug\\cert.crt");
    if (!crt.open(QIODevice::ReadOnly))
    {
        return;
    }

    conf.setLocalCertificate(QSslCertificate(&crt));
    m_request->setSslConfiguration(conf);

    QObject::connect(m_manager,&QNetworkAccessManager::finished, this, &TestNet::GetWebFinished);

    QJsonObject form;
    form.insert("fuMgrVersion", "1.0.1");
    form.insert("fuMgrHash", "86cb0ce0b6f4242fee4ed8f7f6e44ca9520049d0f82cee0d041d56deb9287c1a");

    QByteArray postArray = QJsonDocument(form).toJson();
    m_request->setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    m_request->setHeader(QNetworkRequest::ContentLengthHeader,postArray.size());
    m_manager->post(*m_request, postArray);
}

void TestNet::GetWeb()
{
    m_manager = new QNetworkAccessManager();
    m_request = new QNetworkRequest(QUrl("https://www.baidu.com/"));

    QSslConfiguration conf = m_request->sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    m_request->setSslConfiguration(conf);

    QObject::connect(m_manager,&QNetworkAccessManager::finished,this,&TestNet::GetWebFinished);
    m_manager->get(*m_request);
}

void TestNet::GetWebFinished(QNetworkReply *reply)
{
    qDebug() << reply->error() << endl;
    qDebug() << reply->readBufferSize() << endl;

    //转换为utf-8编码，这样就可以显示中文了
    QTextCodec *codec = QTextCodec::codecForName("utf8");
    QString getData = codec->toUnicode(reply->readAll());
    qDebug() << getData << endl;

    //输出文件
    QFile out_file("One.html");
    out_file.open(QIODevice::Text | QIODevice::WriteOnly);

    out_file.write(getData.toUtf8());

    out_file.close();

    qDebug() << reply->readAll() << endl;
    qDebug() << "finished" << endl;
}
